package com.ciban.smarthome.module.net.communication;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import com.ciban.smarthome.common.utils.ConvertUtils;

public class NetworkUDP extends Network {

	public NetworkUDP(String ip, String port) {
		super(ip, port);
	}

	public NetworkUDP() {
		super();
	}

	@Override
	public String sendData(final String cmd) throws Exception {
		String result = null;
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket();
			socket.setSoTimeout(3000);

			InetAddress ipHost = InetAddress.getByName(ip);
			byte[] bs = ConvertUtils.stringToByte(cmd);

			DatagramPacket pack = new DatagramPacket(bs, bs.length, ipHost,
					Integer.parseInt(port));
			socket.send(pack);

			byte[] tempReData = new byte[127];
			pack = new DatagramPacket(tempReData, tempReData.length);
			socket.receive(pack);

			result = ConvertUtils.bytes2hex(pack.getData(), pack.getLength());

			tempReData = null;
			bs = null;
		} catch (SocketException e) {
			throw new SocketException("连接异常");
		} catch (UnknownHostException e) {
			throw new UnknownHostException("主机异常");
		} catch (IOException e) {
			throw new IOException("读取异常");
		}
		return result;
	}

}
